import * as echarts from 'echarts';
import ReactECharts from 'echarts-for-react';
import React, { useRef, useState } from 'react';
import { fitChartSize } from '../utils/tools';

export interface StationEfficiencyData {
  stationId?: number;
  convertRatio?: number;
  stationName?: string;
}

interface EfficiencyRankingProps {
  data: StationEfficiencyData[];
}

// 设置最大长度
const maxLength = 5; // 调整为10以便测试
// 定义一个函数来截断文字并添加省略号
function truncateText(text: string, maxLength: number) {
  if (text.length > maxLength) {
    return text.substring(0, maxLength) + '...';
  }
  return text;
}

const EfficiencyRanking: React.FC<EfficiencyRankingProps> = ({ data }) => {
  const [tooltipContent, setTooltipContent] = useState<string>('');
  const [tooltipVisible, setTooltipVisible] = useState<boolean>(false);
  const [tooltipPosition, setTooltipPosition] = useState<{ top: number; left: number }>({
    top: 0,
    left: 0,
  });

  const containerRef = useRef<HTMLDivElement>(null);

  const updateTooltipPosition = (event: React.MouseEvent) => {
    const containerRect = containerRef.current?.getBoundingClientRect();
    if (containerRect) {
      const tooltipHeight = 40; // 预估的 tooltip 高度
      const tooltipWidth = 100; // 预估的 tooltip 宽度
      const isBottomHalf = event.clientY - containerRect.top > containerRect.height / 2;
      const isRightHalf = event.clientX - containerRect.left > containerRect.width / 2;

      setTooltipPosition({
        top: isBottomHalf
          ? event.clientY - containerRect.top - tooltipHeight - 10
          : event.clientY - containerRect.top + 10,
        left: isRightHalf
          ? event.clientX - containerRect.left - tooltipWidth - 10
          : event.clientX - containerRect.left + 10,
      });
    }
  };

  const handleMouseEnter = (convertRatio: any, stationName: string, event: React.MouseEvent) => {
    // 尝试将 convertRatio 转换为数字
    let numericRatio = parseFloat(convertRatio);

    // 检查转换后的值是否为有效数字
    if (!isNaN(numericRatio)) {
      setTooltipContent(`${stationName} : ${numericRatio.toFixed(2)}%`);
    } else {
      console.warn(`Expected a number for convertRatio, but got: ${convertRatio}`);
      setTooltipContent(`${stationName} : N/A`);
    }

    setTooltipVisible(true);
    updateTooltipPosition(event);
  };

  const handleMouseMove = (event: React.MouseEvent) => {
    updateTooltipPosition(event);
  };

  const handleMouseLeave = () => {
    setTooltipVisible(false);
  };

  const renderGaugeOption = (convertRatio: number, stationName: string) => {
    const truncatedName = truncateText(stationName, maxLength);

    return {
      tooltip: {
        show: false, // 禁用内置的 tooltip
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '2%',
        top: '-20%',
        containLabel: true,
      },
      series: [
        {
          name: '转换效率',
          type: 'gauge',
          startAngle: 200,
          endAngle: -20,
          min: 0,
          max: 100,
          axisLine: {
            lineStyle: {
              width: 7,
              color: [
                [
                  convertRatio / 100,
                  new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    { offset: 0, color: '#2173fe' },
                    { offset: 1, color: '#02a9fb' },
                  ]),
                ],
                [1, '#DCDCDC'],
              ],
            },
          },
          axisLabel: {
            show: false, // 隐藏刻度上的文字
          },
          axisTick: {
            show: true,
            splitNumber: 4, // 每个大刻度分成 5 个小刻度
            length: -2,
            lineStyle: {
              width: 1,
              color: '#214073',
            },
          },
          splitLine: {
            show: false,
            length: -2,
            lineStyle: {
              color: '#214073',
              width: 1,
              cap: 'round',
              dashOffset: 1,
              join: 'round',
            },
          },
          pointer: {
            show: false,
          },
          detail: {
            formatter: (value: number) => {
              if (Number.isInteger(value)) {
                return `{integer|${value}}{percent|%}`;
              } else {
                const [integerPart, decimalPart] = value.toFixed(2).split('.');
                return `{integer|${integerPart}}{decimal|.${decimalPart}}{percent|%}`;
              }
            },
            color: '#C4D4F1',
            fontSize: fitChartSize(20),
            offsetCenter: [0, '10%'], // 调整文字的位置
            rich: {
              integer: {
                fontSize: fitChartSize(20),
                color: '#C4D4F1',
              },
              decimal: {
                fontSize: fitChartSize(12),
                color: '#C4D4F1',
              },
              percent: {
                fontSize: fitChartSize(12),
                color: '#C4D4F1',
              },
            },
          },
          title: {
            show: false,
          },
          data: [
            {
              value: convertRatio,
            },
          ],
        },
        {
          name: '外层装饰1',
          type: 'pie',
          radius: ['75%', '83%'],
          startAngle: 165,
          endAngle: 15,
          hoverAnimation: false,
          labelLine: {
            show: false,
          },
          data: [
            {
              value: 35,
              itemStyle: {
                color: 'rgb(31,68,131)',
              },
            },
            {
              value: 75,
              itemStyle: {
                color: 'transparent',
              },
            },
          ],
        },
        {
          name: '外层装饰2',
          type: 'pie',
          radius: ['75%', '83%'],
          startAngle: 75,
          endAngle: -75,
          hoverAnimation: false,
          labelLine: {
            show: false,
          },
          data: [
            {
              value: 25,
              itemStyle: {
                color: 'rgb(31,68,131)',
              },
            },
            {
              value: 75,
              itemStyle: {
                color: 'transparent',
              },
            },
          ],
        },
      ],
      title: {
        text: truncatedName,
        left: 'center',
        bottom: '20%',
        textStyle: {
          color: '#5381CC',
          fontSize: fitChartSize(12),
          overflow: 'truncate',
          ellipsis: '...',
        },
      },
    };
  };

  return (
    <div
      ref={containerRef}
      style={{
        display: 'flex',
        justifyContent: 'space-around',
        height: '',
        overflow: 'hidden',
        position: 'relative', // 确保 tooltip 可以相对于容器定位
      }}
    >
      {data.map(({ stationId, convertRatio, stationName }) => (
        <div
          key={stationId}
          style={{ width: '33.333%' }}
          onMouseEnter={(event) => handleMouseEnter(convertRatio ?? 0, stationName ?? '--', event)}
          onMouseMove={handleMouseMove}
          onMouseLeave={handleMouseLeave}
        >
          <ReactECharts
            option={renderGaugeOption(convertRatio ?? 0, stationName ?? '--')}
            style={{ width: '100%', height: fitChartSize(160) }}
          />
        </div>
      ))}
      {tooltipVisible && (
        <div
          style={{
            position: 'absolute',
            top: tooltipPosition.top,
            left: tooltipPosition.left,
            backgroundColor: 'rgba(3, 25, 54, 0.7)',
            border: '1px solid #4c8fce',
            color: '#C4D4F1',
            padding: '10px 10px',
            borderRadius: '3px',
            pointerEvents: 'none', // 确保 tooltip 不会干扰鼠标事件
            fontSize: fitChartSize(12),
          }}
        >
          {tooltipContent}
        </div>
      )}
    </div>
  );
};

export default EfficiencyRanking;
